<template>
  <div class="detail">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-position="right"
      label-width="130px"
    >
      <div class="form-data">
        <el-form-item label="父级菜单" prop="pid">
          <el-select
            v-model.number="postForm.pid"
            placeholder="父级菜单"
            style="width:100%"
            @change="changePid"
          >
            <el-option :value="0" label="顶级菜单" />
            <el-option v-for="item in configOptions" :key="item.id" :value="item.id" :label="item.cn_name" />
          </el-select>
        </el-form-item>
        <el-form-item label="配置名称" prop="cn_name">
          <el-input
            v-model="postForm.cn_name"
            placeholder="配置名称"
            style="width: 100%"
          />
        </el-form-item>
        <div v-show="showConfig">
          <el-form-item label="字段名称" prop="en_name">
            <el-input
              v-model="postForm.en_name"
              placeholder="字段名称"
              style="width: 100%"
            />
            <span class="form-item-tips">请输入英文，不要输入中文</span>
          </el-form-item>
          <el-form-item label="配置项类型" prop="type">
            <el-select
              v-model.number="postForm.type"
              placeholder="配置项类型"
              style="width:100%"
              @change="handleTypeChange"
            >
              <el-option v-for="(item, index) in item_type_name" :key="index" :value="index + 1" :label="item" />
              <!-- <el-option :value="1" label="单行文本框" />
              <el-option :value="2" label="单选按钮" />
              <el-option :value="3" label="复选框" />
              <el-option :value="4" label="下拉菜单" />
              <el-option :value="5" label="文本域" />
              <el-option :value="6" label="富文本" />
              <el-option :value="7" label="单图片" />
              <el-option :value="8" label="多图片" />
              <el-option :value="9" label="附件" />
              <el-option :value="10" label="整型" />
              <el-option :value="11" label="浮点型" /> -->
            </el-select>
          </el-form-item>
          <el-form-item
            v-show="(postForm.type === 2 || postForm.type === 3 || postForm.type === 4) ? true : false"
            label="可选值"
            prop="values"
          >
            <el-input
              v-model="postForm.values"
              type="textarea"
              placeholder="可选值"
              style="width: 100%"
            />
            <span class="form-item-tips">配置项的值，用英文,进行数据分割</span>
          </el-form-item>
          <el-form-item label="提示" prop="tips">
            <el-input
              v-model="postForm.tips"
              placeholder="提示"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item
            v-show="!(postForm.type === 3 || postForm.type === 6 || postForm.type === 7 || postForm.type === 8 || postForm.type === 9)"
            label="默认值"
            prop="value"
          >
            <el-input
              v-model="postForm.value"
              :disabled="isEdit"
              type="textarea"
              placeholder="默认值"
              style="width: 100%"
            />
          </el-form-item>
        </div>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model.number="postForm.sort"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model.number="postForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </div>

      <sticky :class-name="'sub-navbar'">
        <el-button
          v-loading="loading"
          type="success"
          style="margin-left: 10px"
          @click="submitForm"
        >
          {{ isEdit ? '编辑' : '添加' }}
        </el-button>
      </sticky>

    </el-form>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import { item_type_name } from '@/utils'
import { getAllConfigParentNode, getChildrenCount, getByID, addConfig, editConfig } from '@/api/system-config'

const fields = {
  name: '配置名称',
  title: '字段名称'
}

const validateRequire = (rule, value, callback) => {
  if (!value || value === '' || value.trim() === '') {
    const errMsg = fields[rule.field] + '为必填项'
    callback(new Error(errMsg))
  } else {
    callback()
  }
}
const validateEnName = (rule, value, callback) => {
  if (!(/^\w{1,80}$/.test(value))) {
    const errMsg = '字段名称只能包含英文字母、数字、_、-'
    // this.showMessage(errMsg, 'error')
    callback(new Error(errMsg))
  } else {
    callback()
  }
}

export default {
  name: 'SystemConfigDetail',
  components: { Sticky },
  props: {
    id: {
      type: Number,
      default: 0
    },
    pid: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      isEdit: false,
      loading: false,
      configOptions: [],
      showConfig: false,
      item_type_name,
      postForm: {
        pid: 0,
        cn_name: '',
        en_name: '',
        type: '',
        values: '',
        tips: '',
        value: '',
        sort: 1,
        status: 1
      },
      rules: {
        pid: [
          { required: true, message: '父级菜单不能为空' },
          { type: 'number', message: '父级菜单值格式不正确' }
        ],
        cn_name: [
          { required: true, message: '配置名称不能为空' },
          { validator: validateRequire, trigger: 'blur' }
        ],
        en_name: [],
        sort: [
          { required: true, message: '排序不能为空' },
          { type: 'number', message: '排序值格式不正确' }
        ],
        status: [
          { required: true, message: '状态不能为空' },
          { type: 'number', message: '状态值格式不正确' }
        ]
      }
    }
  },
  watch: {
    'postForm.pid': {
      handler(val) {
        if (val === 0) {
          this.rules.en_name = []
          this.showConfig = false
        } else {
          this.rules.en_name = [
            { required: true, message: '字段名称不能为空' },
            { validator: validateEnName, trigger: 'blur' }
          ]
          this.showConfig = true
        }
      },
      deep: true
    }
  },
  methods: {
    submitForm() {
      if (!this.loading) {
        this.loading = true
        this.$refs.postForm.validate((valid, fields) => {
          // 判断规则是否通过验证
          if (valid) {
            const config = Object.assign({}, this.postForm)
            config.type = config.type || 0
            // console.log(config)
            if (!this.isEdit) {
              addConfig(config).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            } else {
              config.id = this.id
              editConfig(config).then(response => {
                this.$notify({
                  title: '成功',
                  message: response.msg,
                  type: 'success',
                  duration: 2000
                })
                this.$emit('ended')
              }).catch(() => {
                this.loading = false
              })
            }
          } else {
            this.loading = false
            for (const key in fields) {
              if (fields.hasOwnProperty(key)) {
                const element = fields[key]
                this.$message({
                  message: element[0].message,
                  type: 'error',
                  duration: 2000
                })
                return false
              }
            }
          }
        })
      }
    },
    getConfigByID() {
      if (this.id !== 0) {
        getByID(this.id).then(response => {
          if (!response.data || response.data.length === 0) {
            this.isEdit = false
            this.changePid(this.pid)
            return
          }
          const {
            pid,
            cn_name,
            en_name,
            type,
            values,
            tips,
            value,
            sort,
            status
          } = response.data
          this.postForm = {
            pid,
            cn_name,
            en_name,
            type,
            values,
            tips,
            value,
            sort,
            status
          }
          this.isEdit = true
        }).catch(() => {
          this.isEdit = false
          this.toDefault()
        })
      } else {
        this.isEdit = false
        this.changePid(this.pid)
      }
    },
    toDefault() {
      this.$refs.postForm.resetFields()
      this.loading = false
    },
    getAllConfigNode() {
      getAllConfigParentNode().then(response => {
        const { data } = response
        this.configOptions = data
        this.postForm.pid = this.pid
        this.getConfigByID()
      })
    },
    changePid(value) {
      getChildrenCount(value).then(response => {
        const { count } = response
        this.postForm.sort = count + 1
      })
    },
    handleTypeChange() {
      this.postForm.values = ''
      this.postForm.value = ''
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
